package com.view.comp.ImageCroping.ui
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.ByteArray;
	
	import spark.components.Button;
	
	[Event(name="imageUploaded", type="flash.events.Event")]
	
	public class BrowserImageButton extends Button
	{
		public function BrowserImageButton()
		{
			super();
			
			label = 'Browse';
			
			_photoUploader = new ImageUploader();
			_photoUploader.addEventListener( ImageUploader.FILE_LOADED_EVENT, onUploadComplete);
			_photoUploader.addEventListener( ImageUploader.FILE_BROWSE_CANCELED_EVENT, cancelOpenBrowserFileWindow);
			this.addEventListener(MouseEvent.CLICK, openBrowseFileWindow);
		}
		
		
		/**
		 * Handles the uploading
		 */		
		private var _photoUploader:ImageUploader;
		
		/**
		 * Limit the size of the images that can be uploaded. 
		 */		
		private var _uploadLimitInMB:Number = 2;

		/**
		 * Setter for the image limit.
		 */
		public function set uploadLimitInMB(value:Number):void
		{
			_uploadLimitInMB = value;
		}
		
		/**
		 * Getter for the Image Bynary Data.
		 */
		public function get imageData():ByteArray
		{
			return _photoUploader.imageData;
		}
		
		/**
		 * Opens the OS window for browsing local files.
		 * @param event
		 * 
		 */		
		private function openBrowseFileWindow(event:MouseEvent):void
		{
			enabled = false;
			_photoUploader.uploadLimitInMB = _uploadLimitInMB;
			_photoUploader.onBrowseClicked(event);
		}
		
		/**
		 * Enable the button again, when the selection is canceled.
		 * @param event
		 * 
		 */		
		private function cancelOpenBrowserFileWindow(event:Event):void
		{
			enabled = true;
		}
		
		/**
		 * 
		 * @param event
		 * 
		 */		
		private function onUploadComplete(event:Event):void
		{
			dispatchEvent(new Event('imageUploaded'));
			enabled = true;
		}
		
	}
}